import { collection_motion_name, motionmodeListgroupItemDataState, motionmodeListgroupItemtext, start_collection_mo1, start_collection_mo2, start_collection_state, train_working, train_end, mo1, mo2, tor1, tor2, send_rate } from '$lib/data';
import { send_serial_emit, recv_serial_event } from '$lib/link';

import { invoke } from '@tauri-apps/api/core'

import { fromStore } from 'svelte/store';
import { cancelmotion } from './utils';

export function start_collection(motion_name: string) {
    fromStore(start_collection_state).current = true;

    fromStore(collection_motion_name).current = motion_name;
    fromStore(start_collection_mo1).current = [];
    fromStore(start_collection_mo2).current = [];

    
    send_serial_emit('c');

}

export function end_collection() {
    fromStore(start_collection_state).current = false;

    send_serial_emit('d');
    
    setTimeout(save_collection,100);

}

async function save_collection() {
    const filename = fromStore(collection_motion_name).current;
    const mo1 = fromStore(start_collection_mo1).current;
    const mo2 = fromStore(start_collection_mo2).current;

    let save_collectio_msg = await invoke('save_file', {filename: filename, mo1: mo1, mo2: mo2})
        .then((res) =>
            res
        )
        .catch((e) => console.error(e));
    console.log(save_collectio_msg);
}

export async function load_collection(filename: string) {
    fromStore(train_end).current = false;
    console.log("load_collection");

    while(fromStore(train_working).current){
        let load_collection_msg = await invoke('send_data', {filename: filename, time: fromStore(send_rate).current})
        .then((res) =>
            res
        )
        .catch((e) => console.error(e));

        console.log(load_collection_msg);
    }

    fromStore(train_end).current = true;

    cancelmotion();

}

export async function find_file() {
    let find_file_msg = await invoke('find_file')
        .then((res) =>
            res
        )
        .catch((e) => console.error(e));
    console.log(find_file_msg);
    (find_file_msg as Array<string>).forEach(file => {
        // 获取文件名的前缀（假设前缀是数字）
        const prefix = file.split("_")[0];
      
        // 将前缀转换为数字
        const index = parseInt(prefix, 10);
        let targetArray = fromStore(motionmodeListgroupItemtext).current;
        let targetArrayState = fromStore(motionmodeListgroupItemDataState).current;
      
        // 检查前缀是否为有效数字
        if (!isNaN(index) && index >= 0) {
          // 如果目标位置已经有值，将其放入数组中
          if (targetArray[index] = "") {

          } else {
            targetArray[index] = file.split("_")[1]; // 直接赋值
            targetArrayState[index] = true;

          }
        }
      });
}

export async function delete_file(filename_prefix: number) {
    let delete_file_msg = await invoke('delete_file', {filenamePrefix: filename_prefix})
        .then((res) =>
            res
        )
        .catch((e) => console.error(e));
    console.log(delete_file_msg);
}

export async function demo_load_collection_mo1(filename: string) {

    let load_collection_msg = await invoke('get_data_mo1', {filename: filename})
        .then((res) =>
            res
        )
        .catch((e) => console.error(e));
    console.log(load_collection_msg);

    fromStore(mo1).current = load_collection_msg as Array<number>;
    fromStore(mo1).current = fromStore(mo1).current.map(num => num / 45);
    fromStore(tor1).current = fromStore(mo1).current.map(num => num / 10 / (Math.random() * 0.2 + 0.9) );
}

export async function demo_load_collection_mo2(filename: string) {

    let load_collection_msg = await invoke('get_data_mo2', {filename: filename})
        .then((res) =>
            res
        )
        .catch((e) => console.error(e));
    console.log(load_collection_msg);

    fromStore(mo2).current = load_collection_msg as Array<number>;
    fromStore(mo2).current = fromStore(mo2).current.map(num => -(num / 45));
    fromStore(tor2).current = fromStore(mo2).current.map(num => num / 10 / (Math.random() * 0.2 + 0.9) );
}